<template>
  <div class="change-management">
    <NavTitle title="变更信息" showRightIcon />
    <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
      <template #operator>
        <div style="margin-top: 16px">
          <a-button type="primary" @click="addNamespace">
            <PlusOutlined />
            新增
          </a-button>
        </div>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'branchType'">
          <span
            class="ellipsis"
            :title="`${branchTypeOptions.find((v: any) => v.value == record.branchType)?.label || '--'}`"
          >
            {{ branchTypeOptions.find((v: any) => v.value == record.branchType)?.label || '--' }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="table-operation">
            <a @click="handelDetail(record)">详情</a>
            <a @click="handelEdit(record)">编辑</a>
            <a @click="handelDelete(record)">删除</a>
          </div>
        </template>
      </template>
    </Table>

    <BasicModal
      ref="showActionModal"
      :title="`${ModalName[showType]}-变更`"
      width="800px"
      :confirmLoading="editChangeLoading"
      @emit-callback-fn="modalCallbackFn"
    >
      <template #content><SchemaForm ref="formRef" /></template>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { ModalName, ModalType } from '@/enums/commonEnum';
import { createVNode } from 'vue';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import {
  getChangeMgmtList,
  addChangeMgmtList,
  updateChangeMgmtList,
  queryChangeMgmtList,
  deleteChangeMgmtList,
} from '@/api/applicationManagement';
import { storeToRefs } from 'pinia';
import { useApplicationStore } from '@/store/modules/app';
// import { formatToDatetime } from '@/utils/DateUtil';
const counterStore = useApplicationStore();
const { componentData } = storeToRefs(counterStore);

const emits = defineEmits(['updateLoading']);
const branchTypeOptions = [
  { label: '新建', value: 1 },
  { label: '关联', value: 2 },
];

const columns = [
  { dataIndex: 'id', title: '变更编码', align: 'center', ellipsis: true },
  { dataIndex: 'name', title: '变更名称', align: 'center', ellipsis: true },
  { dataIndex: 'reason', title: '变更原因', align: 'center', ellipsis: true },
  { dataIndex: 'branchType', title: '分支', align: 'center', ellipsis: true },
  { dataIndex: 'branch', title: '变更分支', align: 'center', ellipsis: true },
  { dataIndex: 'description', title: '描述', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'id',
      label: '变更编码',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      vIf: ({}) => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
    {
      field: 'name',
      label: '变更名称',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
    {
      field: 'reason',
      label: '变更原因',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      component: 'Input',
    },
    {
      field: 'description',
      label: '描述',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      componentProps: {
        rows: 4,
      },
      component: 'InputTextArea',
    },
    {
      field: 'branchType',
      label: '分支',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      componentProps: {
        options: branchTypeOptions,
      },
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(showType.value);
      },
      defaultValue: 1,
      component: 'RadioGroup',
    },
    {
      field: 'branch',
      label: '变更分支',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      // componentProps: {
      //   addonBefore: 'feature/',
      //   placeholder: '请输入',
      // },
      required: true,
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
    // {
    //   field: 'branchTime',
    //   colon: false,
    //   colProps: {
    //     span: 12,
    //   },
    //   componentProps: {
    //     addonBefore: formatToDatetime(new Date(), '_YYYYMMDD_'),
    //   },
    //   component: 'Input',
    // },
    {
      field: 'creator',
      label: '创建人',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      vIf: ({}) => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
    {
      field: 'createTime',
      label: '创建时间',
      labelWidth: 90,
      colProps: {
        span: 24,
      },
      vIf: ({}) => {
        return [ModalType.detail].includes(showType.value);
      },
      component: 'Input',
    },
  ] as FormSchema[],
});

const showType = ref<ModalType>(ModalType.detail);
const showActionModal = ref<any>();
const tableRef = ref<any>('');
const editChangeLoading = ref<boolean>(false);

const addNamespace = () => {
  showType.value = ModalType.add;
  showActionModal.value.showModal();
};

const handelDetail = async (record: any) => {
  showType.value = ModalType.detail;
  const data = await queryChangeMgmtList(record.id);
  showActionModal.value.showModal(data, '关闭');
  nextTick(() => {
    formRef.setSchemaFormProps({ disabled: true });
    formRef.setFieldsValue(data);
  });
};

const handelEdit = (record: any) => {
  showType.value = ModalType.edit;
  showActionModal.value.showModal(record);
  nextTick(() => {
    formRef.setFieldsValue(record);
  });
};

const handelDelete = async (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“变更管理：${record.name}”这一项数据吗？`),
    async onOk() {
      await deleteChangeMgmtList(record.id).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};

const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  let parameObj: Application.addChangeMgmtParams = {
    ...data,
    componentLabel: componentData.value.label,
  };
  editChangeLoading.value = true;
  if (showType.value == ModalType.add) {
    await addChangeMgmtList(parameObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editChangeLoading.value = false;
      });
  }
  if (showType.value == ModalType.edit) {
    await updateChangeMgmtList({ id: obj.propsData.id, ...parameObj })
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editChangeLoading.value = false;
      });
  }
};

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      componentLabel: componentData.value.label,
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await getChangeMgmtList(parameObj)
    .then((res) => {
      const data = {
        total: res.totalCount,
        current: res.currentPage,
        pageSize: res.pageSize,
        records: res?.records || [],
      };
      return data;
    })
    .finally(() => {
      emits('updateLoading', false);
    });
};
</script>

<style scoped lang="less">
:deep(.ant-form-item-no-colon) {
  display: none;
}
:deep(.ant-input-group-addon) {
  color: #00000040;
  background-color: #f5f5f5;
  border-color: #d9d9d9;
}
</style>
